<template>
	<view class="flipbook-viewport" ref="flipbookViewport" :rect="rect" :change:rect="updateRenderData" postMessage="postMessage">
		<view class="container">
			<view class="flipbook">
				<view class="imgItem" v-for="(item,index) in imgUrl" :key="item.index" :style="`background-image:url(${item})`">
					<view v-if="index != 0" class="gradient"></view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		computed: {
			rect() {
				return {
					width: this.width,
					height: this.height,
					fileUrl: this.fileUrl,
				}
			}
		},
		data() {
			return {
				width: uni.getSystemInfoSync().windowWidth,
				height: uni.getSystemInfoSync().windowHeight + 'px',
				fileUrl: '',
				imgUrl: []
			}
		},
		onLoad() {
			this.height = uni.getSystemInfoSync().windowHeight + 'px'

			// this.fileUrl = plus.io.convertLocalFileSystemURL("_doc/电子签章文件/酒店装修合同.pdf")
			
			// 假设你有一个app内文件的绝对路径
			this.readFileAsStream("_doc/电子签章文件/酒店装修合同.pdf").then(arrayBuffer => {
			  // 在这里处理文件流，例如发送文件流
			  this.fileUrl = arrayBuffer
			}).catch(error => {
			  console.error("文件流读取失败:", error);
			});
		},
		methods:{
			//文件路径转base64
			readFileAsStream(filePath) {
			  return new Promise((resolve, reject) => {
			    plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
			      entry.file(function(file) {
			        var reader = new plus.io.FileReader();
			        reader.onloadend = function(e) {
			          // 在这里，e.target.result 就是文件的ArrayBuffer形式的数据
			          resolve(e.target.result);
			        };
			        reader.onerror = function(e) {
			          reject(e);
			        };
			        reader.readAsDataURL(file);
			      }, reject);
			    }, reject);
			  });
			},
			onViewArr(op){
				this.imgUrl = op.arr
			}
		}
	}
</script>
<script lang="renderjs" module="turnjs">
	import '@/utils/jquery-1.7.min.js';
	import turn from '@/utils/turn.js';
	
	// 引入PDF.js
	import pdfjsLib from '@/utils/pdfjs-dist/build/pdf';
	import pdfjsWorker from "@/utils/pdfjs-dist/build/pdf.worker.entry";
	pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
	
	export default {
		data() {
			return {
				fileUrl: '',
				width: '',
				height: '',
				imgArr: []
			}
		},
		methods: {
			async init(){
				let pdfAsArray = this.convertDataURIToBinary(this.fileUrl);
				console.log(pdfAsArray);
				// this.imgArr = await this.convertPDFToImage(this.fileUrl)
				// await this.postMessage()
				// this.onTurn();
			},
			// base64编码转换
			convertDataURIToBinary(dataURI) {
				let BASE64_MARKER = ';base64,'; //声明文件流编码格式
				//[RFC2045]中有规定: Base64-行不能超过76字符，超过则添加回车换行符。因此需要把base64字段中的换行符，回车符给去掉。
				let base64Index = (dataURI + '').indexOf(BASE64_MARKER) + BASE64_MARKER.length;
				let newUrl = dataURI;
				newUrl = dataURI.substring(base64Index).replace(/[\n\r]/g, '');
				let raw = newUrl;
				try {
					raw = window.atob(newUrl); //这个方法在ie内核下无法正常解析。
				} catch (e) {
					console.error(e);
				}
				let rawLength = raw.length;
				//转换成pdf.js能直接解析的Uint8Array类型
				let array = new Uint8Array(new ArrayBuffer(rawLength));
				for (let i = 0; i < rawLength; i++) {
					array[i] = raw.charCodeAt(i) & 0xff;
				}
				return array;
			},
			//推送信息到视图
			postMessage(e,ownerInstance){
				this.$ownerInstance.callMethod('onViewArr',{
					arr: this.imgArr
				})
			},
			async convertPDFToImage(pdfUrl) {
			  // 加载PDF文档
			  const loadingTask = pdfjsLib.getDocument({data:pdfUrl});
			  const pdf = await loadingTask.promise
			  let pages = [];
			  for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
			    // 获取页面
			    const page = await pdf.getPage(pageNum);
			    // 获取视口
			    const viewport = page.getViewport(1);
					viewport.width = uni.getSystemInfoSync().windowWidth
					viewport.height = uni.getSystemInfoSync().windowHeight
			    // 创建canvas元素
			    const canvas = document.createElement('canvas');
			    const context = canvas.getContext('2d');

			    canvas.height = viewport.height;
			    canvas.width = viewport.width;
					
			    const renderContext = {
			      canvasContext: context,
			      viewport: viewport
			    };
			    // 渲染页面
			    await page.render(renderContext).promise;
					
			    // 转换canvas为图片
			    const imgData = canvas.toDataURL('image/jpeg', 1.5);
			 
			    // 将图片数据推送到数组中
			    pages.push(imgData);
			  }
			 
			  // 返回所有页面的图片数组
			  return pages;
			},
			updateRenderData(newVal, oldVal) {
				let {
					width,
					height,
					fileUrl
				} = newVal;
				this.width = width;
				this.height = height;
				this.fileUrl = fileUrl;
				if(fileUrl){
					this.init();
				}
			},
			onTurn() {
				$(".flipbook").turn({
						acceleration: true,
						// autoCenter: true,
						display: 'double',
						// display: 'single',
						height: this.height,
						width: this.width,
						elevation: 600,
						gradients: true,
						threshold: 0.7,
						when: {
							turned: function(e, page) {
								/*console.log('Current view: ', $(this).turn('view'));*/
							},
						},
					})
					.on("last", function(event) {
						alert("当前为最后一页");
					})
					.on("click", function(event) {
						$(this)
							.turn(event.offsetX < $(this).height() >>> 1 ? "previous" : "next")
					})
			}
		}
	}
</script>
<style lang="scss">
	.father {
		position: relative;
	}

	.fixed {
		position: fixed;
		width: 100%;
		height: 100%;
		/* top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1; */
	}

	.abs {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
	}

	.flipbook-viewport {
		overflow: hidden;
		width: 100%;
		height: 100%;

		.container {
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 0 auto;
		}

		.flipbook ::v-deep .page {
			background-color: white;
			background-repeat: no-repeat;
			background-size: cover;

			-webkit-box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
			-moz-box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
			-ms-box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
			-o-box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
			box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);

			img {
				-webkit-touch-callout: none;
				-webkit-user-select: none;
				-khtml-user-select: none;
				-moz-user-select: none;
				-ms-user-select: none;
				user-select: none;
				margin: 0;
			}
		}
		
		.flipbook ::v-deep .even .gradient{
			position:absolute;
			top:0;
			left:0;
			width:100%;
			height:100%;
			background-image:url(../../static/right-border.png);
			background-position:right top;
			background-repeat: repeat-y;
		}
		
		.flipbook ::v-deep .odd .gradient{
			position:absolute;
			top:0;
			left:0;
			width:100%;
			height:100%;
			background-image:url(../../static/left-border.png);
			background-position:left top;
			background-repeat: repeat-y;
		}
		
		.flipbook .page-wrapper{
			-webkit-perspective:2000px;
			-moz-perspective: 2000px;
			-ms-perspective: 2000px;
			perspective: 2000px;
		}

		.shadow {
			-webkit-transition: -webkit-box-shadow 0.5s;
			-moz-transition: -moz-box-shadow 0.5s;
			-o-transition: -webkit-box-shadow 0.5s;
			-ms-transition: -ms-box-shadow 0.5s;

			-webkit-box-shadow: 0 0 20px #ccc;
			-moz-box-shadow: 0 0 20px #ccc;
			-o-box-shadow: 0 0 20px #ccc;
			-ms-box-shadow: 0 0 20px #ccc;
			box-shadow: 0 0 20px #ccc;
		}
	}
</style>